import React from 'react';
import {Popup, PopupTitle, Checkbox, ScrollView, DragColumns} from "@/components/k-view";
import {ColumnPopupProps} from "./type";
import {
    Text,
    View,
    CheckboxGroup,
    HStack,
    Image,
    Pressable,
    Button,
    ButtonText, VStack
} from "@gluestack-ui/themed";
import {useImmer} from "use-immer";
import {arrToMaps} from "@/utils/modules/format";
import {useWindowDimensions} from "react-native";

const CustomColumnsPopup = <V, >(props: ColumnPopupProps<V>) => {
    const {
        isVisible,
        valueKey,
        dispatch,
        title,
        columns,
        value,
        max = 12,
        min = 6,
        onConfirm,
        onCancel,
    } = props;
    const [{selectCols, labelMaps}, updateState] = useImmer({
        selectCols: new Array<string>(),
        labelMaps: arrToMaps(columns, valueKey),
    });
    const windowHeight = useWindowDimensions().height;

    React.useEffect(() => {
        if (isVisible) init();
    }, [value, isVisible]);

    const disabledMax = React.useMemo(() => {
        return selectCols.length >= max
    }, [selectCols.length, max]);

    const disabledMin = React.useMemo(() => {
        return selectCols.length <= min
    }, [selectCols.length, min])

    // 获取选中的values
    function getSelectValues() {
        return value.map(item => item[valueKey]);
    }

    function init() {
        updateState(draft => {
            draft.selectCols = getSelectValues();
        });
    }


    function handleChange(keys: string[]) {
        updateState(draft => {
            draft.selectCols = keys
        })
    }

    function handleClose() {
        dispatch({
            type: "close"
        });
    }

    // 删除选中的指标
    function handleRemoveSelect(item: string | number) {
        if (disabledMin) return
        updateState(draft => {
            draft.selectCols = draft.selectCols.filter(key => key !== item);
        })
    }

    // 选项是否选中
    function isSelect(name: string) {
        return selectCols.includes(name);
    }

    // 拖拽结束排序
    function handleReleaseRow(key: string | number, currentOrder: string[]) {
        updateState(draft => {
            draft.selectCols = currentOrder.map(index => selectCols[parseInt(index)]);
        });
    }

    // 处理确认
    function handleConfirm() {
        handleClose();
        onConfirm && onConfirm(selectCols);
    }


    return (
        <Popup
            isVisible={isVisible}
            mode={"bottom"}
            dispatch={dispatch}
            scrollOffset={50}
            propagateSwipe={true}
            swipeDirection={undefined}
        >
            <View
                borderTopLeftRadius={"$lg"}
                borderTopRightRadius={'$lg'}
                bg={"$white"}
            >
                <PopupTitle title={title} onRightClick={handleClose}></PopupTitle>
                <HStack
                    borderBottomWidth={0.5}
                    borderColor={"$borderLight500"}
                >
                    <View
                        p={15}
                        pb={0}
                        w={"50%"}
                        borderRightWidth={0.5}
                        borderColor={"$borderLight500"}

                    >
                        <Text color={"$textLight600"} size={"md"}>可选指标（{columns.length}）</Text>
                        <Text color={"$textLight800"} mt={"$5"} mb={"$6"}>展示数据</Text>
                        <ScrollView
                            h={windowHeight / 2}
                        >
                            <CheckboxGroup
                                value={selectCols}

                                onChange={handleChange}
                            >
                                {
                                    columns.map((item, index) => (
                                        <Checkbox
                                            iconSize={20}
                                            aria-label={item.label}
                                            mb={"$6"}
                                            value={item[valueKey]}
                                            isDisabled={(disabledMax ? !isSelect(item[valueKey]) && disabledMax : isSelect(item[valueKey]) && disabledMin)}
                                            key={index}
                                        >
                                            <View
                                                pl="$2"
                                            >
                                                <Text
                                                    color={selectCols.includes(item[valueKey]) ? '$primary500' : "$trueGray400"}
                                                    size={"sm"}
                                                >{item.label}</Text>
                                            </View>
                                        </Checkbox>
                                    ))
                                }
                            </CheckboxGroup>
                        </ScrollView>
                    </View>

                    <View
                        p={15}
                        pb={0}
                        w={"50%"}
                    >
                        <Text mb={"$6"} size={"md"} color={"$textLight600"}>已选指标（{selectCols.length}/{max}）</Text>

                        <DragColumns
                            labelMaps={labelMaps}
                            data={selectCols}
                            style={{flex:1}}
                            showsVerticalScrollIndicator={false}
                            onReleaseRow={handleReleaseRow}
                            onRemove={handleRemoveSelect}
                        >
                        </DragColumns>

                    </View>
                </HStack>

                <HStack
                    py={10}
                    pr={15}
                    alignItems={"center"}
                >
                    <Pressable onPress={init}>
                        <VStack
                            alignItems={"center"}
                            mx={"$5"}
                        >
                            <Image
                                w={"$5"}
                                h={'$5'}
                                alt={"重置"}
                                source={require('@/theme/assets/images/icon/reset.png')}
                            ></Image>
                            <Text color={"$textLight950"} size={"xs"}>重置</Text>
                        </VStack>
                    </Pressable>

                    <Button flex={1} onPress={handleConfirm}>
                        <ButtonText size={"sm"}>应用</ButtonText>
                    </Button>
                </HStack>
            </View>
        </Popup>
    );
};

export default CustomColumnsPopup;